﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Sgr.AspNetCore.ActionFilters.AuditLogs;
using Sgr.Indentity.Application.Commands;

namespace Sgr.Indentity.Controllers
{
    /// <summary>
    /// 安全校验服务接口
    /// </summary>
    [Route("api/v1/sgr/secrets")]
    [ApiController]
    [Authorize]
    [Produces("application/json")]
    [Tags("Secret")]
    public class SecretController : ControllerBase
    {
        private readonly IMediator _mediator;

        /// <summary>
        /// 初始化安全校验控制器
        /// </summary>
        /// <param name="mediator">中介者服务</param>
        public SecretController(IMediator mediator)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        }

        /// <summary>
        /// 执行密码二次校验
        /// </summary>
        /// <param name="command">密码校验请求信息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <remarks>
        /// 示例请求:
        ///
        ///     POST /api/v1/sgr/secrets/password-verify
        ///     {
        ///         "tokenType": 1,
        ///         "password": "your_password",
        ///         "timestamp": "2025-04-02T10:00:00Z",
        ///         "nonce": "random_string",
        ///         "signature": "calculated_signature"
        ///     }
        ///
        /// </remarks>
        /// <response code="200">校验成功，返回临时校验令牌</response>
        /// <response code="400">请求参数验证失败</response>
        /// <response code="401">未经授权的访问</response>
        /// <response code="429">请求过于频繁</response>
        [HttpPost("password-verify")]
        [EnableRateLimiting("RateLimiterPolicy.Sgr.Identity")]
        [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status429TooManyRequests)]
        [AuditLogActionFilter("密码二次校验")]
        public async Task<ActionResult<string>> VerifyPasswordAsync([FromBody] SecondPasswordVerifyCommond command, System.Threading.CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(command, cancellationToken);
            return !result.IsSuccess || result.Data == null
                ? this.CustomBadRequest(result.Message)
                : Ok(result.Data);
        }
    }
}